package cn.italkcloud.cph.config.sys;

import cn.italkcloud.cph.config.exception.BusinessException;
import cn.italkcloud.cph.constants.SysConstant;
import cn.italkcloud.cph.constants.enums.FailedEnum;
import cn.italkcloud.cph.entity.dto.UserAuthDTO;
import cn.italkcloud.cph.helper.AuthHelper;
import cn.italkcloud.cph.utils.StringUtil;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author dominate
 * @since 2024/1/11
 **/
public class RequestContent {


    private static final String REQUEST_CONTENT_ATTR_USER = "Content-User";

    /**
     * 获取当前请求用户
     *
     * @return UserAuthDTO 请求用户
     * @throws BusinessException 登录状态异常
     */
    public static UserAuthDTO getUser() throws BusinessException {
        HttpServletRequest request = getRequest();
        Object contentUser = request.getAttribute(REQUEST_CONTENT_ATTR_USER);
        if (null != contentUser) {
            return (UserAuthDTO) contentUser;
        }
        // 解析请求头
        String token = request.getHeader(SysConstant.HEADER_TOKEN);
        if (StringUtil.isEmpty(token)) {
            throw BusinessException.create(FailedEnum.IS_PRIVATE);
        }
        UserAuthDTO user = AuthHelper.parseWithValid(token);
        request.setAttribute(REQUEST_CONTENT_ATTR_USER, user);
        return user;
    }

    /**
     * 设置请求里的用户
     *
     * @param user 用户
     */
    public static void setUser(UserAuthDTO user) {
        HttpServletRequest request = getRequest();
        request.setAttribute(REQUEST_CONTENT_ATTR_USER, user);
    }

    public static String getToken() {
        HttpServletRequest request = getRequest();
        return request.getHeader(SysConstant.HEADER_TOKEN);
    }


    /**
     * 判断登录状态
     *
     * @return 是否登录
     */
    public static boolean isLogin() {
        HttpServletRequest request = getRequest();
        String token = request.getHeader(SysConstant.HEADER_TOKEN);
        if (StringUtil.isEmpty(token)) {
            return false;
        }
        return AuthHelper.isValid(token);
    }


    private static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
    }


}
